@page "/admin/files"

@using System.IO
@using System.Collections.Generic
@inject IWebHostEnvironment Environment
@inject IJSRuntime JSRuntime

@layout AdminLayout
@rendermode InteractiveServer

<PageTitle>文件管理</PageTitle>

<AdminRouteTemplate>
    <div class="admin-container">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2>文件管理</h2>
            <button class="btn btn-primary" @onclick="RefreshFiles">刷新</button>
        </div>

        @if (!string.IsNullOrEmpty(_errorMessage))
        {
            <div class="alert alert-danger">@_errorMessage</div>
        }

        <div class="card">
            <div class="card-header">
                <h5 class="card-title mb-0">文件列表</h5>
            </div>
            <div class="card-body">
                @if (_files.Any())
                {
                    <div class="table-responsive">
                        <table class="table table-striped">
                            <thead>
                                <tr>
                                    <th>文件名</th>
                                    <th>大小</th>
                                    <th>修改时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach (var file in _files)
                                {
                                    <tr>
                                        <td>@file.Name</td>
                                        <td>@FormatFileSize(file.Length)</td>
                                        <td>@file.LastWriteTime.ToString("yyyy-MM-dd HH:mm")</td>
                                        <td>
                                            <button class="btn btn-sm btn-primary" @onclick="() => DownloadFile(file.Name)">下载</button>
                                        </td>
                                    </tr>
                                }
                            </tbody>
                        </table>
                    </div>
                }
                else
                {
                    <div class="text-center py-5">
                        <p class="text-muted">files目录中暂无文件</p>
                    </div>
                }
            </div>
        </div>
    </div>
</AdminRouteTemplate>

@code {
    private List<FileInfo> _files = new List<FileInfo>();
    private string _errorMessage = string.Empty;

    protected override void OnInitialized()
    {
        LoadFiles();
    }

    private void LoadFiles()
    {
        try
        {
            var filesDirectory = new DirectoryInfo(Path.Combine(Environment.WebRootPath, "files"));
            if (filesDirectory.Exists)
            {
                _files = filesDirectory.GetFiles().Select(f => new FileInfo
                {
                    Name = f.Name,
                    Length = f.Length,
                    LastWriteTime = f.LastWriteTime
                }).ToList();
            }
        }
        catch (Exception ex)
        {
            _errorMessage = $"加载文件列表时出错: {ex.Message}";
        }
    }

    private async Task DownloadFile(string fileName)
    {
        // 使用JavaScript在新窗口中打开下载链接，保持认证状态
        await JSRuntime.InvokeVoidAsync("open", $"/api/files/{fileName}", "_blank");
    }

    private void RefreshFiles()
    {
        LoadFiles();
        StateHasChanged();
    }

    private string FormatFileSize(long bytes)
    {
        string[] sizes = { "B", "KB", "MB", "GB", "TB" };
        double len = bytes;
        int order = 0;
        while (len >= 1024 && order < sizes.Length - 1)
        {
            order++;
            len = len / 1024;
        }

        return $"{len:0.##} {sizes[order]}";
    }

    public class FileInfo
    {
        public string Name { get; set; } = string.Empty;
        public long Length { get; set; }
        public DateTime LastWriteTime { get; set; }
    }
}